package com.xindz.hgq.database.greendao.view;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;

import com.blankj.utilcode.util.ToastUtils;
import com.orhanobut.logger.Logger;
import com.xindz.hgq.R;
import com.xindz.hgq.adapter.SimpleAdapter;
import com.xindz.hgq.app.App;
import com.xindz.hgq.base.BaseTitleActivity;
import com.xindz.hgq.base.options.BaseActivityOptions;
import com.xindz.hgq.database.greendao.bean.DaoSession;
import com.xindz.hgq.database.greendao.bean.JoinStudentToTeacher;
import com.xindz.hgq.database.greendao.bean.SchoolBean;
import com.xindz.hgq.database.greendao.bean.StudentBean;
import com.xindz.hgq.database.greendao.bean.TeacherBean;
import com.xindz.hgq.utils.greendao.DbManager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @name HGQBase
 * @class name：com.xindz.hgq.database.greendao.view
 * @describe describe
 * @anthor XINDZ
 * @time 2018/5/21 15:40
 * @change
 * @chang time
 * @class describe
 */
public class GdRelationalExampleActivity extends BaseTitleActivity {
    @BindView(R.id.bt_gd_re_create)
    Button btGdReCreate;
    @BindView(R.id.bt_gd_re_relation)
    Button btGdReRelation;
    @BindView(R.id.rcv_gd_relation)
    RecyclerView rcvGdRelation;
    @BindView(R.id.bt_gd_re_create_school)
    Button btGdReCreateSchool;
    @BindView(R.id.bt_gd_query_student)
    Button btGdQueryStudent;
    private DaoSession daoSession;
    private List<SchoolBean> schools;
    private List<TeacherBean> teachers;
    private ArrayList<StudentBean> students;
    private ArrayList<JoinStudentToTeacher> joins;
    private List<String> dataStringList;
    private SimpleAdapter adapter;

    @Override
    public BaseActivityOptions setOption() {
        return new BaseActivityOptions().openTitle();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gd_relation);
        ButterKnife.bind(this);
        showLeftBack();
        setTitleText("GD 表关系");
        daoSession = App.app.getDaoSession();
        rcvGdRelation.setLayoutManager(new LinearLayoutManager(this));
        dataStringList = new ArrayList<>();
        adapter = new SimpleAdapter(R.layout.item_gd_relation, dataStringList);
        rcvGdRelation.setAdapter(adapter);
    }

    @OnClick({R.id.bt_gd_re_create, R.id.bt_gd_re_relation, R.id.bt_gd_re_create_school
            , R.id.bt_gd_query_student})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_gd_re_create_school:
                createSchool();
                ToastUtils.showShort("生成学校结束");
                break;
            case R.id.bt_gd_re_create:
                createTeacher();
                createStudent();
                ToastUtils.showShort("生成教师、学生结束");
                break;
            case R.id.bt_gd_re_relation:
                createRelational();
                ToastUtils.showShort("生成学生教师关系结束");
                break;
            case R.id.bt_gd_query_student:
                getStudentData();
                ToastUtils.showShort("查询学生表结束");
                break;
        }
    }

    /**
     * 生成学校
     */
    private void createSchool() {
        schools = new ArrayList<>();
        for (int i = 1; i <= 2; i++) {
            String schoolId = "" + i + System.currentTimeMillis();
            String schoolName = "第 " + i + " 小学";
            SchoolBean schoolBean = new SchoolBean(schoolId, schoolName);
            schools.add(schoolBean);
        }
        daoSession.runInTx(new Runnable() {
            @Override
            public void run() {
                daoSession.getSchoolBeanDao().deleteAll();
                daoSession.getSchoolBeanDao().insertInTx(schools);
                Logger.i("生成学校结束");

            }
        });

    }

    /**
     * 生成老师 并为老师设置学校
     */
    private void createTeacher() {
        teachers = new ArrayList<>();
        for (int i = 1; i <= 2; i++) {
            SchoolBean schoolBean = schools.get(i - 1);
            String schoolId = schoolBean.getSchoolId();

            String teacherIdOne = "1" + i + System.currentTimeMillis();
            String teacherNameOne = "第" + i + "小学语文老师 " + i;
            TeacherBean teacherBeanOne = new TeacherBean(teacherIdOne, teacherNameOne, schoolId);
//            teacherBeanOne.setSchool(schoolBean);

            String teacherIdTwo = "2" + i + System.currentTimeMillis();
            String teacherNameTwo = "第" + i + "小学数学老师 " + i;
            TeacherBean teacherBeanTwo = new TeacherBean(teacherIdTwo, teacherNameTwo, schoolId);
//            teacherBeanTwo.setSchool(schoolBean);

            String teacherIdThree = "3" + i + System.currentTimeMillis();
            String teacherNameThree = "第" + i + "小学英语老师 " + i;
            TeacherBean teacherBeanThree = new TeacherBean(teacherIdThree, teacherNameThree, schoolId);
//            teacherBeanThree.setSchool(schoolBean);

            teachers.add(teacherBeanOne);
            teachers.add(teacherBeanTwo);
            teachers.add(teacherBeanThree);

        }
        daoSession.runInTx(new Runnable() {
            @Override
            public void run() {
                daoSession.getTeacherBeanDao().deleteAll();
                daoSession.getTeacherBeanDao().insertInTx(teachers);
                Logger.i("生成教师结束");

            }
        });
    }

    /**
     * 生成学生 并为学生设置学校
     */
    private void createStudent() {
        students = new ArrayList<>();
        for (int i = 1; i <= 2; i++) {
            SchoolBean schoolBean = schools.get(i - 1);
            String schoolId = schoolBean.getSchoolId();

            String studentIdOne = "1" + i + System.currentTimeMillis();
            String studentNameOne = "赵" + i;
            StudentBean studentBeanOne = new StudentBean(studentIdOne, studentNameOne, schoolId);
//            studentBeanOne.setSchool(schoolBean);

            String studentIdTwo = "2" + i + System.currentTimeMillis();
            String studentNameTwo = "钱" + i;
            StudentBean studentBeanTwo = new StudentBean(studentIdTwo, studentNameTwo, schoolId);
//            studentBeanTwo.setSchool(schoolBean);

            String studentIdThree = "3" + i + System.currentTimeMillis();
            String studentNameThree = "孙" + i;
            StudentBean studentBeanThree = new StudentBean(studentIdThree, studentNameThree, schoolId);
//            studentBeanThree.setSchool(schoolBean);

            String studentIdFour = "4" + i + System.currentTimeMillis();
            String studentNameFour = "李" + i;
            StudentBean studentBeanFour = new StudentBean(studentIdFour, studentNameFour, schoolId);
//            studentBeanFour.setSchool(schoolBean);

            students.add(studentBeanOne);
            students.add(studentBeanTwo);
            students.add(studentBeanThree);
            students.add(studentBeanFour);
        }
        daoSession.runInTx(new Runnable() {
            @Override
            public void run() {
                daoSession.getStudentBeanDao().deleteAll();
                daoSession.getStudentBeanDao().insertInTx(students);
                Logger.i("生成学生结束");
            }
        });
    }

    /**
     * 设置学生老师的关联关系
     * <p>
     * 1查询学校列表
     * 2遍历学校列表,根据学校获取学校的学生,和老师列表
     * 3遍历学校的学生列表,为学校写学生选择老师
     * 4构建关系
     */
    private void createRelational() {
        List<SchoolBean> schoolBeans = daoSession.getSchoolBeanDao().loadAll();
        joins = new ArrayList<>();
        if (schoolBeans != null) schools = schoolBeans;
        for (SchoolBean schoolBean : schools) {
            List<StudentBean> students = schoolBean.getStudents();
            List<TeacherBean> teachers = schoolBean.getTeachers();
            String teacherId0 = teachers.get(0).getTeacherId();
            String teacherId1 = teachers.get(1).getTeacherId();
            String teacherId2 = teachers.get(2).getTeacherId();
            for (int i = 0; i < students.size(); i++) {
                StudentBean studentBean = students.get(i);
                String studentId = studentBean.getStudentId();
                JoinStudentToTeacher jst0 = new JoinStudentToTeacher(null, studentId, teacherId0);
                joins.add(jst0);
                //根据奇偶选择不同的老师
                if (i % 2 == 0) {
                    JoinStudentToTeacher jst1 = new JoinStudentToTeacher(null, studentId, teacherId1);
                    joins.add(jst1);
                } else {
                    JoinStudentToTeacher jst2 = new JoinStudentToTeacher(null, studentId, teacherId2);
                    joins.add(jst2);
                }

            }

        }
        daoSession.runInTx(new Runnable() {
            @Override
            public void run() {
                daoSession.getJoinStudentToTeacherDao().deleteAll();
                daoSession.getJoinStudentToTeacherDao().insertInTx(joins);
                Logger.i("生成学生教师关系结束");

            }
        });
    }

    private void getStudentData() {
        ArrayList<String> studentStrList = new ArrayList<>();
        List<StudentBean> studentBeans = daoSession.getStudentBeanDao().loadAll();
        if (studentBeans == null) return;
        for (StudentBean studentBean : studentBeans) {
            if (null == studentBean) break;
            StringBuilder stuSb = new StringBuilder();
            stuSb.append("姓名:").append(studentBean.getStudentName()).append("\n");
            //使用除 xxDeep() 方法外的方法获取Entity 不会获取Entity内的其他Entity 在getxx()方法时会抛出NullPointerException
            //即studentBean.getSchool() 会抛出异常
//            if (studentBean.getSchool() != null) {
//                stuSb.append("学校:").append(studentBean.getSchool().getSchoolName()).append("\n");
//            }
            List<TeacherBean> teachers = studentBean.getTeachers();
            if (null != teachers) {
                for (TeacherBean teacherBean : teachers) {
                    stuSb.append("老师").append(teacherBean.getTeacherName()).append("\n");
                }
            }
            studentStrList.add(stuSb.toString());
        }
        dataStringList.clear();
        int size = studentStrList.size();
        dataStringList.addAll(studentStrList);
        adapter.notifyDataSetChanged();
    }

}
